package cn.com.coding.framework.security;

import cn.com.coding.common.lang.ResT;
import cn.com.coding.common.utils.JwtUtil;
import cn.com.coding.common.utils.RedisUtil;
import cn.com.coding.system.service.UserInfoService;
import cn.hutool.core.map.MapUtil;
import cn.hutool.json.JSONUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.time.LocalDate;

/**
 * 认证成功处理器
 *
 * @author mxz
 */
@Component
public class LoginSuccessHandler implements AuthenticationSuccessHandler {

    @Autowired
    private UserInfoService userInfoService;

    @Autowired
    private JwtUtil jwtUtil;

    @Autowired
    RedisUtil redisUtil;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request, HttpServletResponse response, Authentication authentication) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream = response.getOutputStream();

        // 生成jwt，并放置到请求头中
        String jwt = jwtUtil.generateToken(authentication.getName());
        System.out.println(jwt);
        response.setHeader(jwtUtil.getHeader(), jwt);

        String user = request.getParameter("username");

        ResT result = ResT.ok().setData(MapUtil.builder().put("user", userInfoService.getByUserName(user)).put("msg", "操作成功").build());

        LocalDate date = LocalDate.now();
        redisUtil.hincr("mxz_user_login_success_record", String.valueOf(date), 1);
        outputStream.write(JSONUtil.toJsonStr(result).getBytes("UTF-8"));

        outputStream.flush();
        outputStream.close();
    }

}
